// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Text;
using JetBrains.Annotations;
using MySql.Data.MySqlClient;

namespace SnapObjects.Data.MySql
{
    public class MySqlByteArrayTypeMapping : ByteArrayTypeMapping
    {
        private readonly int _maxSpecificSize;
        private const int MaxSize = 8000;

        /// <summary>
        ///     Initializes a new instance of the <see cref="SqlServerByteArrayTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="System.Data.DbType" /> to be used. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        public MySqlByteArrayTypeMapping(
            [NotNull] string dbTypeName,
            [CanBeNull] DbType? dbType = System.Data.DbType.Binary,
            int? size = null)
            : base(dbTypeName, dbType, size)
        {
            _maxSpecificSize = CalculateSize(size);
        }

        private static int CalculateSize(int? size)
        {
            return size.HasValue && size < MaxSize ? size.Value : MaxSize;
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new MySqlByteArrayTypeMapping(
                           dbTypeName,
                           this.DbType,
                           size);
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected override void ConfigureParameter(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {

            var length = _maxSpecificSize;

            if (parameter.Value != null && parameter.Value != DBNull.Value)
            {
                if (parameter.Value is byte[] bytes)
                {
                    length = bytes.Length;

                    if (length > MaxSize)
                    {
                        ((MySqlParameter)parameter).MySqlDbType = MySqlDbType.LongBlob;
                    }
                }
            }

            parameter.Size = length;
        }

        /// <summary>
        ///     Generates the SQL representation of a literal value.
        /// </summary>
        /// <param name="value">The literal value.</param>
        /// <returns>
        ///     The generated string.
        /// </returns>
        protected override string GenerateNonNullSqlLiteral(object value)
        {
            var builder = new StringBuilder();
            builder.Append("0x");

            foreach (var @byte in (byte[])value)
            {
                builder.Append(@byte.ToString("X2", CultureInfo.InvariantCulture));
            }

            return builder.ToString();
        }
    }
}
